import {Component, Inject, OnInit, ViewEncapsulation} from '@angular/core';
import {SCRIPT_LOADER, ScriptLoader} from "@core/script-loader/script-loader";
import {ParentService} from "@train/parent/parent.service";
import {
  SNSResult, StudentStestScoreSummary, StudentTestScoreLineChartVO,
  StudentTestScoreSimple, TestScoreStandardResultVO
} from "@interface/index";
import {ActivatedRoute, Params} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import {TeacherService} from "@train/teacher/teacher.service";


const SINGLE_TEST_SCORE_OPTIONS = (params) => {
  console.log(params);
  return {
    xAxis: { //X轴
      type: 'time',
      axisTick: {
        show: false //刻度隐藏
      },
      axisLine: { //线
        lineStyle: {
          color: '#e5e5e5'
        },
      },
      axisLabel: {
        color: '#999999',
        fontSize: 12,
        interval: 0,
        // rotate:"45"
      },
      splitNumber: 8,
      splitLine: {
        show: true,
        interval: 'auto',
        lineStyle: {
          color: ['#FBFBFB']
        }
      }
      // data: params['testDates']
    },
    yAxis: {
      inverse: params.inverse,
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: {
        color: '#999999',
        fontSize: 12,
        interval: 0,
        rotate: 40,
        formatter: function (value) {
          if (params.testScoreType === 1) { //非主观题
            return value + (params.unit === '秒' ? 's' : params.unit);
          }
          for (let i = 0, j = params.standardList.length; i < j; i++) {
            let min = params.standardList[i]['minValue'],
              max = params.standardList[i]['maxValue'];
            if (!min && max && value <= max) {
              return params.standardList[i].testGrade;
            }
            if (min && !max && min <= value) {
              return params.standardList[i].testGrade;
            }
            if (min && max && min <= value && value <= max) {
              return params.standardList[i].testGrade;
            }
          }
        }
      },
      axisTick: {
        show: false
      },
      // min: 0,
      // max: 300,
      splitNumber: 2, //间隔数量
      splitLine: {
        lineStyle: {
          color: ['#e5e5e5'],
          type: 'dotted'
        }
      }
    },
    series: [
      {
        data: params['curScores'],
        markPoint: {// 最大值拐角原点
          label: {
            show: true,
            position: ['-50%', -15],
            formatter(value) {
              let scoreValue = value['value'], grade = '';
              if (params.testScoreType === 1) { //非主观题
                return scoreValue + (params.unit === '秒' ? 's' : params.unit);
              }
              for (let i = 0, j = params.standardList.length; i < j; i++) {
                let min = params.standardList[i]['minValue'],
                  max = params.standardList[i]['maxValue'];
                if (!min && max && scoreValue <= max) {
                  grade = params.standardList[i].testGrade;
                }
                if (min && !max && min <= scoreValue) {
                  grade = params.standardList[i].testGrade;
                }
                if (min && max && min <= scoreValue && scoreValue <= max) {
                  grade = params.standardList[i].testGrade;
                }
              }
              return grade;
            }
          },
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: "#D14A59"
            }
          },
          data: [
            {
              type: params.inverse ? 'min' : 'max',
            }
          ]
        },//end markPoint
        name: '学员当日成绩',
        type: 'line',
        smooth: true,
        itemStyle: {
          normal: {
            color: "#4192f3",
          }
        },
        lineStyle: { // 线的粗细
          normal: {
            width: 1.5,
            color: "#4192f3"   // 线条颜色
          }
        },
        symbol: 'circle',// 拐角原点
        symbolSize: 6,
      },
      {
        data: params['avgScores'],
        // data:[200,100,300,400,500,600,700],
        // markPoint: {
        //   data: [
        //     {type: 'max', name: '最大值'},
        //     {type: 'min', name: '最小值'}
        //   ]
        // },
        name: '所有学员当日成绩',
        type: 'line',
        boundaryGap: false,
        smooth: true,
        itemStyle: {
          normal: {
            color: "#ff8e00",
            // borderColor: "blue"  // 点边线的颜色
          }
        },
        lineStyle: { // 线的粗细
          normal: {
            width: 1.5,
            color: "#ff8e00"   // 线条颜色
          }
        },
        symbol: 'circle',// 拐角原点
        symbolSize: 6
      }
    ]
  };
};

@Component({
  selector: 'seed-single-test-scores',
  templateUrl: './single-test-scores.component.html',
  styleUrls: ['./single-test-scores.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class SingleTestScoresComponent implements OnInit {

  public showChart: boolean = false;
  public options: Object;
  public echartsIntance: any;
  public paramObj = {
    studentId: 0,
    levelId: 0,
    testModeId: 0,
    testMethodId: 0,
    testItemText: '',
    ageGroupText: '',
    testMethodName: ''
  };
  public studentStestScoreSummary: StudentStestScoreSummary;
  public radarMapObj: StudentTestScoreLineChartVO;
  public firstScoreSimple: StudentTestScoreSimple;
  public standardResult: TestScoreStandardResultVO;

  constructor(
    private parentService: ParentService,
    private teacherService: TeacherService,
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    @Inject(SCRIPT_LOADER) public scriptLoader: ScriptLoader
  ) {
    activatedRoute.params.switchMap((param: Params) => {
      this.paramObj.studentId = +param['studentId'];
      this.paramObj.levelId = +param['levelId'];
      this.paramObj.testModeId = +param['testModeId'];
      this.paramObj.testMethodId = +param['testMethodId'];
      this.eChartsPromise();
      return this.activatedRoute.queryParams;
    }).subscribe((queryParam: Params) => {
      this.paramObj.testItemText = queryParam['testItemText'];
      this.paramObj.ageGroupText = queryParam['ageGroupText'];
      this.paramObj.testMethodName = queryParam['testMethodName'];
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description echart加载完渲染
   */
  eChartsPromise() {
    const eCharts = this.scriptLoader.load('echarts'),
      levelInfo = this.getTestScoreCriteria(),
      scoreLineChart = this.studentTestScoreLineChart();
    Promise.all([eCharts, scoreLineChart, levelInfo]).then((resArray) => {
      if (resArray['2']['data']) {
        this.standardResult = resArray['2']['data'];
      }
      if (resArray['0']['0']['loaded'] && resArray['1']['data']) {
        this.radarMapObj = resArray['1']['data'];
        this.displayECharts(resArray['1']['data']);
      }
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description 组织echart数据结构
   */
  displayECharts(radarMapObj) {
    this.studentStestScoreSummary = radarMapObj['studentStestScoreSummary']; //成绩总结
    this.firstScoreSimple = radarMapObj['currentDayScores'][0];
    const query = {
        inverse: radarMapObj.testScoreSort, //0：倒序，1：顺序
        testScoreType: this.firstScoreSimple.testScoreType, //0代表主观题，1代表非主观题
        unit: this.firstScoreSimple.testScoreType ? this.firstScoreSimple.testScoreDesc : '次', //单位,
        standardList: this.standardResult.standardList, //评分等级
        avgScores: [], //平均成绩
        curScores: [] //当日成绩
      },
      avgScores = radarMapObj['currentDayAvgScores'].reverse(),
      curScores = radarMapObj['currentDayScores'].reverse();
    avgScores.forEach(avgItem => {
      query['avgScores'].push([new Date(this.timestampToTime(avgItem['testDate'])), avgItem['testScore'] + ''])
    });
    curScores.forEach(curItem => {
      query['curScores'].push([new Date(this.timestampToTime(curItem['testDate'])), curItem['testScore'] + ''])
    });
    // dateArray = avgScores.length > curScores.length ? avgScores : curScores;
    // avgScores.forEach(item => {
    //   query['avgScores'].push(item['testScore']);
    // });
    // curScores.forEach(item => {
    //   query['curScores'].push(item['testScore']);
    // });
    // dateArray.forEach(item => {
    //   query['testDates'].push(this.getMonthAndDay(item['testDate']));
    // });
    this.showECharts(query);
  }

  showECharts(query) {
    this.showChart = true;
    this.options = SINGLE_TEST_SCORE_OPTIONS(query);
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description 根据时间戳获取月份和日期
   */
  getMonthAndDay(dateStr) {
    const date = new Date(dateStr);
    return date.getMonth() + 1 + '-' + date.getDate();
  }

  /**
   * @author guoqs1331
   * @time 2018/4/17
   * @description
   */
  studentTestScoreLineChart(): Promise<SNSResult<StudentTestScoreLineChartVO>> {
    const param = {
      "levelId": this.paramObj.levelId,
      "studentId": this.paramObj.studentId,
      "testMethodId": this.paramObj.testMethodId,
      "testModeId": this.paramObj.testModeId
    };
    return this.parentService.studentTestScoreLineChart(param).toPromise();
  }

  /**
   * @description 查询评分标准（教练）
   * @author ouyqx-691
   * @date 2018-4-11
   */
  getTestScoreCriteria() {
    const params = {
      orgUserId: this.authService.getAuthOrgId(),
      itemId: this.paramObj.testMethodId,
      ageId: this.paramObj.levelId
    };
    return this.teacherService.getTestScoreCriteria(params).toPromise();
  }

  timestampToTime(timestamp) {
    let date = new Date(timestamp),//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      Y = date.getFullYear() + "-",
      M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-",
      D = date.getDate() + "";
    return Y + M + D;
  }

  onChartInit(e) {
    this.echartsIntance = e;
  }

  ngOnInit() {
  }

}
